import axios from 'axios';

export default {
    name: 'AFileUploader',
    props: {
        elButtonType: {
            type: String,
        },
        elButtonIcon: {
            type: String,
        },
        elButtonSize: {
            type: String,
        },
        value: {
            type: String,
        },
    },
    data() {
        return {
            filePath: this.value,
            fileInput: null,
            isUploading: false,
            uploadProgress: 0,
            uploadResult: null,
            uploadFilePath: null,
        };
    },
    methods: {
        handleUploadClick() {
            // 创建文件输入元素
            this.fileInput = document.createElement('input');
            this.fileInput.type = 'file';
            this.fileInput.accept = '.jpg,.png,.pdf,.doc,.docx'; // 可根据需要修改

            // 添加到DOM但隐藏
            this.fileInput.style.display = 'none';
            document.body.appendChild(this.fileInput);

            // 绑定文件选择事件
            this.fileInput.addEventListener('change', this.handleFileSelect);

            // 触发文件选择对话框
            this.fileInput.click();
        },

        handleFileSelect(event) {
            const file = event.target.files[0];
            if (!file) return;

            this.isUploading = true;
            this.uploadProgress = 0;
            this.uploadResult = null;

            // 使用Axios上传文件
            this.uploadFileWithAxios(file);

            // 上传完成后清理
            setTimeout(() => {
                this.cleanupFileInput();
            }, 100);
        },

        async uploadFileWithAxios(file) {
            try {
                // 创建FormData对象
                const formData = new FormData();
                formData.append('file', file);

                // 配置Axios请求
                const response = await axios.post('/Api/FileUpload', formData, {
                    headers: {
                        // 'Content-Type': 'multipart/form-data',
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    // 监听上传进度
                    onUploadProgress: (progressEvent) => {
                        const percentCompleted = Math.round(
                            (progressEvent.loaded * 100) / progressEvent.total
                        );
                        this.uploadProgress = percentCompleted;
                    },
                });

                // 处理上传成功响应
                this.uploadResult = {
                    success: true,
                    message: '文件上传成功',
                    data: response.data.result.url,
                };
                this.uploadFilePath = response.data.result.url;

                this.$emit('success', response.data.result.url);
            } catch (error) {
                // 处理上传错误
                console.error('上传失败:', error);

                let errorMessage = '上传过程中发生错误';
                if (error.response) {
                    // 服务器返回错误状态码
                    errorMessage = `上传失败 (${error.response.status}): ${
            error.response.data.message || '服务器错误'
          }`;
                } else if (error.request) {
                    // 请求已发送，但没有收到响应
                    errorMessage = '服务器未响应，请稍后再试';
                }

                this.uploadResult = {
                    success: false,
                    message: errorMessage,
                };
            } finally {
                this.isUploading = false;
            }
        },

        cleanupFileInput() {
            if (this.fileInput) {
                // 移除事件监听器
                this.fileInput.removeEventListener('change', this.handleFileSelect);

                // 从DOM中移除
                document.body.removeChild(this.fileInput);

                // 清除引用
                this.fileInput = null;
            }
        },
    },
    beforeDestroy() {
        // 确保组件销毁前清理
        this.cleanupFileInput();
    },
};